package com.xy.deepclone;


import java.io.*;

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2022/6/10 14:37
 * @description prototype 深拷贝
 */
public class Sheep implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private String color;
    public Sheep friend;

    public Sheep(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    /**
     * 克隆深拷贝 序列化
     *
     * @return
     */
    @Override
    protected Sheep clone() {
        Sheep sheep = null;
        try(
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos)
                ){

            oos.writeObject(this);
            try (
                    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                    ObjectInputStream ois = new ObjectInputStream(bis);
                    ){
                 sheep = (Sheep) ois.readObject();

            }

        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sheep;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}
